var usuariosClass;
usuariosClass = {
    win:null,
    form:null,
    grid:null,
    layout:null,
    idUser: null,
    nameUser: null,
    widgetTab:function () {
        mainTab.addTab("usutab", "Usuarios", "", "-1");
        mainTab.setTabActive("usutab");
        widgetBar(mainTab.cells("usutab"), 3);
    },
    widgetWin:function (text,sw) {
        var me = this,
            windows = new dhtmlXWindows();

        me.win = windows.createWindow('window_1', 0, 0, 675, 210);
        me.win.setText(text);
        me.win.setIcon('icon_09.png');
        me.win.button('park').hide();
        me.win.button('minmax1').hide();
        me.win.denyResize();
        me.win.setModal(1);
        me.win.centerOnScreen();
    },
    widgetForm:function () {
        var me = this,
            str;

        str = [
            { type:"settings", labelWidth:115, inputWidth:250, position:"absolute"  },
            { type:"label", name:"form_label_1", label:"DATOS PERSONALES", width:250, labelWidth:250, labelAlign:"left", labelLeft:10, labelTop:5  },
            { type:"input", name:"usu_nombres", label:"Nombre(s):", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:7, labelTop:35, inputLeft:125, inputTop:35  },
            { type:"input", name:"usu_paterno", label:"Apellido Paterno:", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:7, labelTop:60, inputLeft:125, inputTop:60  },
            { type:"input", name:"usu_materno", label:"Apellido Materno:", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:7, labelTop:85, inputLeft:125, inputTop:85  },
            { type:"input", name:"usu_email", label:"Correo Electrónico:", validate:"NotEmpty,ValidEmail", labelAlign:"right", inputWidth:195, labelLeft:7, labelTop:110, inputLeft:125, inputTop:110  },

            { type:"label", name:"form_label_3", label:"DATOS DE USUARIO", width:250, labelWidth:250, labelAlign:"left", labelLeft:330, labelTop:5  },
            { type:"select", name:"usu_rol", label:"Rol de Usuario:", validate:"NotEmpty", labelAlign:"right", connector:mainPath + "index.php/roles/combo_data", inputWidth:195, labelLeft:335, labelTop:35, inputLeft:453, inputTop:35  },
            { type:"input", name:"usu_login", label:"Login de Usuario:", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:335, labelTop:60, inputLeft:453, inputTop:60  },
            { type:"password", name:"usu_pass", label:"Contraseña:", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:335, labelTop:85, inputLeft:453, inputTop:85  },
            { type:"password", name:"usu_pass2", label:"Repetir Contraseña:", validate:"NotEmpty", labelAlign:"right", inputWidth:195, labelLeft:335, labelTop:110, inputLeft:453, inputTop:110  },
            { type:"checkbox", name:"usu_notificar", label:"Notificar por Email:", checked:true, labelWidth:125, labelAlign:"right", labelLeft:325, labelTop:135, inputLeft:451, inputTop:132  },
            { type:"button", name:"edit_btn", label:"Button", value:"Modificar", width:"75", inputWidth:75, inputLeft:493, inputTop:135  },
            { type:"button", name:"save_btn", label:"Button", value:"Guardar", width:"75", inputWidth:75, inputLeft:573, inputTop:135  }
        ];
        me.form = me.win.attachForm(str);
    },
    onEventForm: function(){
        var me = this;

        me.form.attachEvent("onButtonClick", function (name) {
            switch (name) {
                case 'save_btn':
                    me.onClickButtonSaveData();
                    break;
                case 'edit_btn':
                    me.onClickButtonEditData();
                    break;
            }
        });
    },
    onClickButtonSaveData: function(){
        var me = this,
            id,
            auxFind,
            valCell,
            data,
            resData;

        if (me.form.validate()) {
            data=me.form.getFormData();
            auxFind = me.grid.findCell(data.usu_login, 9);
            valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
            if(valCell == data.usu_login){
                dhtmlx.alert({
                    text:"Error, ya existe el login '"+valCell.toUpperCase()+"', ingrese otro."
                });
            }
            if (data.usu_pass == data.usu_pass2) {
                me.form.send(mainPath + 'index.php/usuarios/save_data', function (loader, response) {
                    resData = response.split('-');
                    if (resData[0] > 0){
                        id = me.grid.uid();
                        me.grid.addRow(id, [resData[0], resData[1], data.usu_rol, data.usu_nombres, data.usu_paterno, data.usu_materno, name, data.usu_email, data.usu_login, '****************']);
                        me.grid.selectRowById(id);
                        me.statusGrid.setText("Numero de Registros: " + me.grid.getRowsNum());
                        actionBar.enableItem('btn_new');
                        me.win.close();
                    }
                    else
                        dhtmlx.alert({
                            text:response
                        });
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, Las constraseña no coiciden."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onClickButtonEditData: function(){
        var me = this,
            data,
            rowId = me.grid.cells(me.grid.getSelectedRowId(), 0).getValue();

        if (me.form.validate()) {
            data = me.form.getFormData();
            if (data.usu_pass == data.usu_pass2) {
                me.form.send(mainPath + 'index.php/usuarios/edit_data?id=' + rowId, function (loader, response) {
                    if (response) {
                        me.grid.clearAll();
                        me.onLoadGridData();
                        me.win.close();
                    }
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, Las constraseña no coiciden."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    widgetGrid:function () {
        var me = this;

        me.statusGrid = mainTab.cells("usutab").attachStatusBar();

        me.grid = mainTab.cells("usutab").attachGrid();
        me.grid.setHeader("Id,Rol,rolCodigo,name,apaterno,amaterno,Nombre(s) y Apellidos,Correo Electronico,Login,Contraseña,Mun. Asignados");
        me.grid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro");
        me.grid.setColAlign("right,left,left,left,left,left,left,left,left,left,center");
        me.grid.setInitWidths("30,*,*,*,*,*,*,*,175,175,100");
        me.grid.setColumnHidden(1, true);
        me.grid.setColumnHidden(2, true);
        me.grid.setColumnHidden(3, true);
        me.grid.setColumnHidden(4, true);
        me.grid.setColumnHidden(5, true);
        me.grid.init();
        me.onLoadGridData();
    },
    onLoadGridData: function(){
        var me = this;

        me.grid.load(mainPath + "index.php/usuarios/grid_data", function () {
            me.grid.groupBy(1);
            /*me.grid.setColumnHidden(1, true);
            me.grid.setColumnHidden(2, true);
            me.grid.setColumnHidden(3, true);
            me.grid.setColumnHidden(4, true);
            me.grid.setColumnHidden(5, true);*/
            me.statusGrid.setText("Numero de Registros: " + me.grid.getRowsNum());
        }, "json");
    },
    onEventActionToolBar: function(){
        var me = this;

        actionBar.attachEvent("onClick", function(itemId){
            switch(itemId){
                case 'btn_asing':
                    me.onClickButtonAsing();
                    break;
                case 'btn_new':
                    me.onClickButtonNew();
                    break;
                case 'btn_edit':
                    me.onClickButtonEdit();
                    break;
                case 'btn_erase':
                    me.onClickButtonErase();
                    break;
                case 'btn_print':
                    me.onClickButtonPrint();
                    break;
                case 'btn_clear':
                    me.onClickButtonClear();
                    break;
            }
        });
    },
    onClickButtonAsing: function(){
        var me =  this,
            rowRol;

        if (me.grid.getSelectedRowId() != null) {
            rowRol = me.grid.cells(me.grid.getSelectedRowId(), 2).getValue();
            if(rowRol == "TRA"){
                me.nameUser = me.grid.cells(me.grid.getSelectedRowId(), 6).getValue();
                me.idUser = me.grid.cells(me.grid.getSelectedRowId(), 0).getValue();
                asigUserClass.widgetMain();
            }
            else
                dhtmlx.alert({
                    text:"Error no puede asignar Municipios a Usuarios de este Rol."
                });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder asignar Municipios."
            });
    },
    onClickButtonNew: function(){
        var me = this;

        me.widgetWin('Adicionar Usuarios',0);
        me.widgetForm();
        me.onEventForm();
        me.form.disableItem('edit_btn');
        me.form.enableItem('save_btn');
        me.form.setItemFocus('usu_nombres');
    },
    onClickButtonEdit: function(){
        var me = this,
            id = me.grid.getSelectedRowId();

        if (id != null) {
            me.widgetWin('Editar Usuarios',2);
            me.widgetForm();
            me.onEventForm();
            me.form.disableItem('save_btn');
            me.form.enableItem('edit_btn');
            me.form.disableItem('usu_rol');
            me.form.disableItem('usu_login');
            me.form.setItemValue('usu_rol', me.grid.cells(id, 2).getValue());
            me.form.setItemValue('usu_nombres', me.grid.cells(id, 3).getValue());
            me.form.setItemValue('usu_paterno', me.grid.cells(id, 4).getValue());
            me.form.setItemValue('usu_materno', me.grid.cells(id, 5).getValue());
            me.form.setItemValue('usu_email', me.grid.cells(id, 7).getValue());
            me.form.setItemValue('usu_login', me.grid.cells(id, 8).getValue());
            me.form.setItemFocus('usu_pass');
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder editar."
            });
    },
    onClickButtonErase: function(){
        var me = this,
            rowId;

        if (me.grid.getSelectedRowId() != null) {
            rowId = me.grid.cells(me.grid.getSelectedRowId(), 0).getValue();
            dhtmlx.confirm({
                text:"¿Esta seguro que quieres eliminar el Ítem?",
                callback:function (status) {
                    if (status == true) {
                        me.grid.deleteSelectedRows();
                        me.statusGrid.setText("Numero de Registros: " + me.grid.getRowsNum());
                        dhtmlxAjax.getSync(mainPath + 'index.php/usuarios/erase_data?id=' + rowId);
                    }
                }
            });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder eliminar."
            });
    },
    onClickButtonPrint: function(){
        if (!searchTab('usuReportTab')) {
            mainTab.addTab("usuReportTab", "Reporte Usuarios", "", "-1");
            mainTab.setTabActive("usuReportTab");
            mainTab.setHrefMode("iframes-on-demand");
            mainTab.setContentHref("usuReportTab",mainPath+'index.php/usuarios/print_data');
        }
        else
            mainTab.setTabActive("usuReportTab");
    },
    onClickButtonClear: function(){
        var me = this;

        me.grid.expandAllGroups();
        me.grid.clearSelection();
    },
    widgetMain:function () {
        var me = usuariosClass;

        if (!searchTab('usutab')) {
            me.widgetTab();
            me.widgetGrid();
            me.onEventActionToolBar();
        }
        else
            mainTab.setTabActive("usutab");
    }
};